#!/bin/sh


if [ -n "$1" ];then
	APPLICATION=$1
else
	APPLICATION=ubuntu-tweak
fi

if [ -n "$2" ];then
	VERSION=$2
else
	VERSION=0.4.7
fi

if [ -n "$3" ];then
	DISTRO=$3
else
	DISTRO=hardy
fi

VERSION=$2
DISTRO=$3

SRC_ROOT=$HOME/Sources/$APPLICATION
BUILD_ROOT=$HOME/Sources/$APPLICATION/dist
UPLOAD_SOURCE=$BUILD_ROOT/UPLOAD_SOURCE
BUILD_DIR=$BUILD_ROOT/$APPLICATION-$VERSION
TARBALL=$BUILD_ROOT/$APPLICATION-$VERSION.tar.gz
ORIGBALL=$BUILD_ROOT/${APPLICATION}_${VERSION}.orig.tar.gz
CHANGELOG=$HOME/Sources/ubuntu-tweak-0.7.x-packaging/debian/changelog

CLEAN_OLD() {
    rm -rf $BUILD_DIR
    rm -rf $SRC_ROOT/debian
    cp -r $HOME/Sources/ubuntu-tweak-0.7.x-packaging/debian $SRC_ROOT
}

if [ ! -f "$ORIGBALL" ]
then
    echo "Cleaning old build..."
    CLEAN_OLD
fi

INFO() {
    echo "Building $APPLICATION-$VERSION for $DISTRO at $BUILD_DIR"
}
INFO

cd $BUILD_DIR

if [ ! -f $UPLOAD_SOURCE ];then
    echo "Build archive and upload source..."

    cd $SRC_ROOT

    if [ ! -f $ORIGBALL ];then
        python setup.py sdist > /dev/null
        mv -v $TARBALL $ORIGBALL
    fi

    tar zxf $ORIGBALL -C $BUILD_ROOT/

    cp -r $SRC_ROOT/debian $BUILD_DIR/debian

    touch $UPLOAD_SOURCE
    debuild -S -sa 1> /dev/null
else
    echo "Build archive without uploading source..."

    cp $SRC_ROOT/debian/changelog $BUILD_DIR/debian/changelog

    REPLACE=`head -1 $CHANGELOG | grep $DISTRO`

    if [ ! -n "$REPLACE" ]; then
        echo "Replace the precise with $DISTRO"
        sed -i "1s/precise/$DISTRO/g" $BUILD_DIR/debian/changelog
    fi

    debuild -S -sd 1> /dev/null
fi
